﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.IO;
using System.Text;

using BetterImageProcessor;
using BetterImageProcessorIndexedResizing;
using BetterImageProcessorQuantization;
using System.Net;
using NHibernate.Criterion;

namespace LIB
{
    public class App_File
    {

        public App_File() { }

        public static string readUrl(string url)
        {
            try
            {
                string result = string.Empty;

                WebRequest wrq = WebRequest.Create(url);
                WebResponse wrs = wrq.GetResponse();

                StreamReader strdr = new StreamReader(wrs.GetResponseStream(), Encoding.UTF8);
                result = strdr.ReadToEnd();

                strdr.Close();
                wrs.Close();
                return result;
            }
            catch (Exception ee)
            {
                return "";
            }
        }
        public static string tienToFile()
        {
            DateTime now = DateTime.Now;
            string year = ConvertUtility.ToString(now.Year);
            string month = (now.Month + 1) < 10 ? "0" + ConvertUtility.ToString(now.Month) : ConvertUtility.ToString(now.Month);
            string day = (now.Day) < 10 ? "0" + ConvertUtility.ToString(now.Day) : ConvertUtility.ToString(now.Day);
            return year + month + day;
        }

        public static void writeFile(string pathFile, string fileData)
        {
            string strPathRoot = new System.Web.Services.WebService().Server.MapPath("\\");
            string pathFolder = strPathRoot;
            string fileName = strPathRoot + pathFile;
            string[] arrPathFile = pathFile.Split('/');
            if (arrPathFile.Length > 1)
            {
                try
                {
                    for (int i = 1; i < arrPathFile.Length - 1; i++)
                    {
                        pathFolder += "/" + arrPathFile[i];
                        if (!Directory.Exists(pathFolder))
                            Directory.CreateDirectory(pathFolder);
                    }
                    if (File.Exists(fileName))
                        File.Delete(fileName);
                    FileStream fs = File.Create(fileName);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.Write(fileData);
                    sw.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                   
                }
            }
        }
        public static void renameFolder(string oldPath, string newPath)
        {
            try
            {
                string current = new System.Web.Services.WebService().Server.MapPath("\\");
                string pathFolder = current;
                string[] arrPathFile = newPath.Split('/');
                if (arrPathFile.Length > 1)
                {

                    for (int i = 1; i < arrPathFile.Length - 1; i++)
                    {
                        pathFolder += "/" + arrPathFile[i];
                        if (!Directory.Exists(pathFolder))
                            Directory.CreateDirectory(pathFolder);
                    }
                }
                oldPath = current + oldPath;
                newPath = current + newPath;
                File.Copy(oldPath, newPath);
                File.Delete(oldPath);
            }
            catch (Exception ex) { }
        }
        public static void delRecruimentFolder(string folder)
        {
            try
            {
                System.IO.Directory.Delete(new System.Web.Services.WebService().Server.MapPath("/" + folder), true);
            }
            catch (Exception ex) { }
        }
        public static void delFile(string filePath)
        {
            filePath = new System.Web.Services.WebService().Server.MapPath(filePath);
            if (File.Exists(filePath))
                File.Delete(filePath);
        }
        public static void genTemplate(string url, string pathFile)
        {
            try
            {
                string result = string.Empty;

                WebRequest wrq = WebRequest.Create(url);
                WebResponse wrs = wrq.GetResponse();

                StreamReader strdr = new StreamReader(wrs.GetResponseStream(), Encoding.UTF8);
                result = strdr.ReadToEnd();
                result = result.Replace("\r", "");
                result = result.Replace("\n", "");
                result = result.Replace("\t", "");

                writeFile(pathFile, result);
                strdr.Close();
                wrs.Close();
            }
            catch (Exception ee)
            { }
        }



        public static string readFile(string sPathFile)
        {
            try
            {
                sPathFile = new System.Web.Services.WebService().Server.MapPath("/" + sPathFile);
                StreamReader file = new StreamReader(sPathFile, Encoding.UTF8);
                string _tmp = file.ReadToEnd();
                file.Close();

                return _tmp;
            }
            catch (IOException e)
            {
                return "";
            }
        }

        public static string getContentTextFile(string sFilePath)
        {
            string strContent = "";
            using (StreamReader rdr = System.IO.File.OpenText(sFilePath))
            {
                strContent = rdr.ReadToEnd();
            }
            return strContent;
        }
        public static string checkFileAnh(FileUpload fileUpload)
        {
            string strFileNameWithPath = fileUpload.PostedFile.FileName;
            string strExtensionName = System.IO.Path.GetExtension(strFileNameWithPath);
            string strFileName = System.IO.Path.GetFileName(strFileNameWithPath);

            // Restrict the user to upload type file
            strExtensionName = strExtensionName.ToLower();
            int fileSize = fileUpload.PostedFile.ContentLength / 1024 / 1024;
            if (fileSize > 4)
            {
                return "Chỉ upload file có kích thước tối đa 4Mb";
            }
            else
            {
                if (strExtensionName != ".jpg" && strExtensionName == ".gif" && strExtensionName == ".png")
                {
                    return "Chỉ upload các file có đuôi jpg, gif hoặc png";
                }
                else
                    return "";
            }
        }

        public static void uploadFileOnSerVer(FileUpload fileUpload, string pathToSave, int maxWThumb, int maxHThumb)
        {
            try
            {
                // get the full path of your computer
                string strFileNameWithPath = fileUpload.PostedFile.FileName;
                // get the extension name of the file
                string strExtensionName = System.IO.Path.GetExtension(strFileNameWithPath);
                // get the filename of user file
                string strFileName = System.IO.Path.GetFileName(strFileNameWithPath);

                // Restrict the user to upload type file
                strExtensionName = strExtensionName.ToLower();
                strFileName = App_File.tienToFile() + "." + strFileName;
                fileUpload.PostedFile.SaveAs(new System.Web.Services.WebService().Server.MapPath(pathToSave) + strFileName);
                
                if (strExtensionName == ".jpg" || strExtensionName == ".gif" || strExtensionName == ".png")
                {
                    ImageProcessor.Resize(fileUpload.FileContent, maxWThumb, maxHThumb, ResizeQuality.HighSpeed).Save(new System.Web.Services.WebService().Server.MapPath(pathToSave + "/thumb/") + strFileName);
                }
               
                   
            }
            catch (Exception ex) { }
        }
        public static string genPathFile(string type,DateTime datetime,int userID,string fileName,bool isMaHoa)
        {
            //exam: /video/2010/11/14/1/test
            if (isMaHoa)
                fileName = ConvertUtility.RC2Encrypt(fileName);
            return type + "/" + datetime.Year + "/" + datetime.Month + "/" + datetime.Day + "/" + userID + "/" + fileName;
        }
        public static string genPathFile(string type, DateTime datetime, int userID)
        {
            return type + "/" + datetime.Year + "/" + datetime.Month + "/" + datetime.Day + "/" + userID;
        }
        public static string genDelPathFile(DateTime datetime)
        {
            //exam: /video/2010/11/14/1
            return "/delete/" + datetime.Year + "/" + datetime.Month + "/" + datetime.Day ;
        }
        public static void uploadFileOnSerVer(FileUpload fileUpload, string strPathFile)
        {
            try
            {
                string strFileNameWithPath = fileUpload.PostedFile.FileName;
                //string strExtensionName = System.IO.Path.GetExtension(strFileNameWithPath);
                string pathToSave = new System.Web.Services.WebService().Server.MapPath("\\"); 
                //exam: /video/2010/11/14/1/test.aspx
                
                string[] arrPathFile = strPathFile.Split('/');
                for (int i = 1; i < arrPathFile.Length - 1; i++)
                {
                    pathToSave += "/" + arrPathFile[i];
                    if (!Directory.Exists(pathToSave))
                        Directory.CreateDirectory(pathToSave);
                }
                string fileName = arrPathFile[arrPathFile.Length-1];
                if (File.Exists(fileName))
                    File.Delete(fileName);
                fileUpload.PostedFile.SaveAs(pathToSave + "/"+ fileName);//+strExtensionName);
                    
            }
            catch (Exception ex) { }
        }
    }
}
